package com.example.keepserver.service.impl;

import com.example.keepserver.dto.UserDTO;
import com.example.keepserver.model.User;
import com.example.keepserver.repository.UserRepository;
import com.example.keepserver.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserServiceImpl implements UserService {
    
    private final UserRepository userRepository;
    
    @Override
    public List<UserDTO> getAllUsers() {
        log.info("获取前10个用户列表");
        List<User> users = userRepository.findTop10ByOrderByCreatedAtDesc();
        log.debug("获取到{}个用户", users.size());
        return users.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    @Override
    public UserDTO getUserById(String userId) {
        log.info("根据ID获取用户: {}", userId);
        Optional<User> userOpt = userRepository.findByUserId(userId);
        
        return userOpt.map(this::convertToDTO).orElse(null);
    }
    
    /**
     * 将用户实体转换为DTO
     * @param user 用户实体
     * @return 用户DTO
     */
    private UserDTO convertToDTO(User user) {
        return UserDTO.builder()
                .username(user.getNickname())
                .userId(user.getUserId())
                .email(user.getEmail())
                .nickname(user.getNickname())
                .avatarUrl(user.getAvatarUrl())
                .gender(user.getGender())
                .location(user.getLocation())
                .followerCount(user.getFollowerCount())
                .followingCount(user.getFollowingCount())
                .postCount(user.getPostCount())
                .createdAt(user.getCreatedAt())
                .build();
    }
} 